package com.utils;

import com.pojo.Emp;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class MyDataConverter  {
  public void register(Emp emp, Map map){
      try {
          //解决BeanUtils不能封装Date类型
          ConvertUtils.register(new Converter() {
              @Override
              public Object convert(Class clazz, Object value) {
                  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                  Date parse = null;
                  try {
                      if (value.equals("") || value == null) {
                          value = "2018-05-25";
                      }
                      parse = format.parse(value.toString());
                  } catch (ParseException e) {
                      e.printStackTrace();
                  }
                  return parse;
              }

          }, Date.class);
          BeanUtils.populate(emp, map);
      } catch (IllegalAccessException | InvocationTargetException e) {
          e.printStackTrace();
      }
  }
}
